package BookManagement.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Borrow {
    //借书类

    private String userName;//借书用户名，外键
    private String bookISBN;//借书ISBN码，外键
    private String bookName;//借书书名
    private String length;//借书时长，以天计算
    private String timeStart;//借书起始时间点
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public Borrow(String bookISBN,String userName,String bookName,String length){
        this.bookISBN=bookISBN;
        this.userName=userName;
        this.bookName=bookName;
        this.timeStart = sdf.format(new Date());
        this.length =(length!=null) ? length : "30";//默认借阅一个月
    }

    //计算剩余时长
    public String getTime(Date currentTime,Date firstTime,String length){//当前时间，借阅时间，时长
        long diff=currentTime.getTime()-firstTime.getTime();
        Calendar currentTimes=dataToCalendar(currentTime);
        Calendar firstTimes=dataToCalendar(firstTime);
        int year=currentTimes.get(Calendar.YEAR)-firstTimes.get(Calendar.YEAR);
        int month=currentTimes.get(Calendar.MONTH)-firstTimes.get(Calendar.MONTH);
        int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH);
        if(day<0){
            month-=1;
            currentTimes.add(Calendar.MONTH,-1);
            day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
        }
        if(month<0){
            month=(month+12)%12;
            year-=1;
        }
        int len = Integer.valueOf(length);
        int days = len - (year*365 + month*30 + day);
        String CountTime = ""+days+"天";
        return CountTime;
    }

    // Date类型转Calendar类型
    public Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }
}
